package com.fmi.chesstern.strategy;

import java.util.ArrayList;

import com.fmi.chesstern.gameboard.GameBoard;
import com.fmi.chesstern.gameboard.GameField;
import com.fmi.chesstern.pieces.ChessPiece;
import com.fmi.chesstern.pieces.ChessPiece.PieceColor;
import com.fmi.chesstern.pieces.ChessPiece.PieceType;

public class KingStrategy implements IGameStrategy {

	public ArrayList<GameField> getValidMoves(GameField currentPosition, GameBoard board) {
		ArrayList<GameField> allMoves = new ArrayList<GameField>();
		PieceColor color = board.getPieces().get(currentPosition.toString()).getColor();
		allMoves.add(new GameField(currentPosition.getRow() - 1, currentPosition.getColumn()));
		allMoves.add(new GameField(currentPosition.getRow() - 1, currentPosition.getColumn() + 1));
		allMoves.add(new GameField(currentPosition.getRow() - 1, currentPosition.getColumn() - 1));
		allMoves.add(new GameField(currentPosition.getRow(), currentPosition.getColumn() + 1));
		allMoves.add(new GameField(currentPosition.getRow(), currentPosition.getColumn() - 1));
		allMoves.add(new GameField(currentPosition.getRow() + 1, currentPosition.getColumn()));
		allMoves.add(new GameField(currentPosition.getRow() + 1, currentPosition.getColumn() + 1));
		allMoves.add(new GameField(currentPosition.getRow() + 1, currentPosition.getColumn() - 1));
		
		ArrayList<GameField> moves = new ArrayList<GameField>();
		for (GameField move : allMoves) {
			if (GameField.isFieldCorrect(move) && isValid(move, board, color)) {
				moves.add(move);
			}
		}
		return moves;
	}
	
	private boolean isValid(GameField goal, GameBoard board, PieceColor color) {
		boolean valid = true;
		ChessPiece piece = board.getPieces().get(goal.toString());
		if (piece != null && piece.getColor() == color) {
			valid = false;
		} else if (isThreatened(goal, board, color)) {
			valid = false;
		}
		return valid;
	}

	private boolean isThreatened(GameField goal, GameBoard board, PieceColor color) {

		boolean isThreatened = false;
		
		ArrayList<GameField> moves = new ArrayList<GameField>();
		moves.add(new GameField(goal.getRow() - 1, goal.getColumn()));
		moves.add(new GameField(goal.getRow() - 1, goal.getColumn() + 1));
		moves.add(new GameField(goal.getRow() - 1, goal.getColumn() - 1));
		moves.add(new GameField(goal.getRow(), goal.getColumn() + 1));
		moves.add(new GameField(goal.getRow(), goal.getColumn() - 1));
		moves.add(new GameField(goal.getRow() + 1, goal.getColumn()));
		moves.add(new GameField(goal.getRow() + 1, goal.getColumn() + 1));
		moves.add(new GameField(goal.getRow() + 1, goal.getColumn() - 1));
		
		for (GameField move : moves) {
			//TODO add more cases
			ChessPiece piece = board.getPieces().get(move.toString());
			if (piece != null && piece.getType() == PieceType.KING && piece.getColor() != color) {
				isThreatened = true;
			}
		}
		return isThreatened;
	}

}
